package com.family.controller;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.print.URIException;

import com.hp.hpl.jena.sparql.pfunction.library.str;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.family.dict.FeatureDict;
import com.family.relation.utils.PublicVirtuoso;

import com.family.relation.utils.StringUtil;

@Controller
@RequestMapping("/relation")
public class Relation {
	
	@Resource
	private FeatureDict dict;
	
	@Resource
	private PublicVirtuoso virtuo;
	
	static String URI = "http://www.ia.cas.cn/baike_baidu/resource/百度资源_";
	
	//map name to jiapu 
	@RequestMapping(value="mapName",produces="text/plain;charset=utf-8")
	@ResponseBody
	public String mapName2Jiapu(String name, String prov, String city, String county, String persons){
//		List<String> list = this.virtuo.MapJiapu(name);
//		List<String> list = this.virtuo.Map2JP("毛泽东", "湖南省", "湘潭市", "韶山市");
		List<String> list = this.virtuo.Map2JP(name, prov, city, county, persons);
		if(list==null||list.isEmpty()){
			return "0";
		}else{
			return StringUtil.getJSON(list);
		}
	}
	
	//map name to baike 
		@RequestMapping(value="mapBaike",produces="text/plain;charset=utf-8")
		@ResponseBody
		public String mapName2Baike(String name){
//			List<String> list = this.virtuo.MapJiapu(name);
//			List<String> list = this.virtuo.Map2JP("毛泽东", "湖南省", "湘潭市", "韶山市");
			String res = this.virtuo.MapBaike(name);
			return res;
		}
	
	@RequestMapping("/addRelation")
	@ResponseBody
	public String addRelation(@RequestParam("triples[]") List<String> triples,@RequestParam("descs[]") List<String> descs,@RequestParam("relatedWorks[]") List<String> relatedWorks){
		String res =null;
		//create the insert data query
		StringBuffer sb = new StringBuffer();
		sb.append("insert data{");
		for(java.util.Iterator<String> it = triples.iterator(); it.hasNext();){
			String tri = it.next();
			String[] strs = tri.split(";;");
			if(strs.length<3) continue;
			System.out.println(strs[0]+","+strs[1]);
			String sub = "<"+URI+strs[0].trim()+">";
			String obj = "<"+URI+strs[2].trim()+">";
//			String pro = "<"+URI+strs[1].trim()+">";
            String pro = "";

            if (strs[1].equals("子女")) {
                pro = "<http://purl.org/vocab/relationship/childOf>";
            }

            if (strs[1].equals("配偶")) {
                pro = "<http://purl.org/vocab/relationship/spouseOf>";
            }
			
			sb.append(sub+" "+pro+" "+obj+".");
		}		
		//create the related work 
		for(java.util.Iterator<String> it = descs.iterator(); it.hasNext();){
			String desc = it.next();
			String[] strs = desc.split(";;");
			if(strs.length<1) continue;
			String sub = "<"+URI+strs[0].trim()+">";
			String pro = "<http://www.library.sh.cn/ontology/relatedWork>";
			
			for(java.util.Iterator<String> it2 = relatedWorks.iterator(); it2.hasNext();){
				String work = it2.next();
				String obj = "<"+work.trim()+">";
				sb.append(sub+" "+pro+" "+obj+".");
			}
		}
		sb.append("}");
System.out.println("["+sb.toString()+"]");
		//end of the creation

        try {
            String url = "http://45.78.35.217:8890/sparql?default-graph-uri=" + URLEncoder.encode("http://www.semlink.cn/graph/baike") + "&query=" + URLEncoder.encode(sb.toString(), "utf8");

//            String url="http://45.78.35.217:8890/sparql?default-graph-uri=http%3A%2F%2Fwww.semlink.cn%2Fgraph%2Fbaike&query=insert%20data{%3Chttp://www.family.com/%E6%AF%9B%E5%B2%B8%E8%8B%B1%3E%20%3Chttp://www.family.com/%E5%84%BF%E5%AD%90%3E%20%3Chttp://www.family.com/%E6%AF%9B%E6%B3%BD%E4%B8%9C%3E.}";
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("content-type", "application/json");
            headers.put("x-api-key", "");
            URL u =  new  URL(url);
            HttpURLConnection conn = (HttpURLConnection)u.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout( 10000 );
            conn.setRequestMethod("POST");
            for (String key : headers.keySet()) {
                conn.addRequestProperty(key, headers.get(key));
            }
            conn.addRequestProperty("host", "45.78.35.217:8890");
            conn.setRequestProperty("Content-Type", "application/json");
            InputStream is = conn.getInputStream();
            String response = streamToString(is);
            is.close();
            System.out.println(response);
            res = response;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    static   public  String streamToString(InputStream is)  throws  IOException {
//        StringBuffer out =  new  StringBuffer();
//         byte [] b =  new   byte [ 4096 ];
//         for  ( int  n; (n = in.read(b)) != - 1 ;) {
//            out.append( new  String(b,  0 , n));
//        }
//         return  out.toString();
//    	 ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream();
//         int   i=-1;
//         while((i=is.read())!=-1){
//         baos.write(i);
//         }
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
        StringBuffer sb = new StringBuffer();
        String str="";
        while ((str = reader.readLine()) != null)
        {
            sb.append(str);
        }
        return sb.toString();
//        return   baos.toString();
    }

    // future work
	@RequestMapping("/getRelevant")
	@ResponseBody
	public void get(List<String> descs){
		/**
		 * 1. add all descs
		 * 2. get all famous people all as candidates, get all relevant bags;
		 * 3. iterate famous people and get the most lose one;
		 */
		
		StringBuffer desc = new StringBuffer();
		for(java.util.Iterator<String> it = descs.iterator(); it.hasNext();){
			desc.append(it.next());
		}
		List<String> featuresOfInput = dict.featureExtract(desc.toString());
		
	}
	
}
